<template>
  <div class="fill-width-height flex-col" style="padding: 12px;">
    <!-- 开始爬取按钮 -->
    <div class="flex-row flex-wrap" style="gap: 12px;padding-bottom: 12px;flex-wrap: wrap;" v-if="isEdit">
      <div class="flex-1" style="min-width: 400px;">
        <TypeMenu :typeList="typeList" v-model="activeId" :isShowActive="false" @itemClick="clickType"/>
      </div>
      <div class="flex-row" >
        <el-button type="primary" size="small" @click="addTask">新增任务</el-button>
        <el-button type="primary" size="small" @click="subscription">订阅文章</el-button>
        <el-button type="success" size="small" @click="editAllImage">全部图片</el-button>
        <el-button type="danger" size="small" @click="deleteBills">多删除</el-button>
        <div style="font-size: 30px;cursor: pointer;margin: 0 5px;" v-if="isEdit">
          <i class="el-icon-setting" @click="setting"></i>
        </div>
      </div>
    </div>
    <el-divider style="margin: 0;"/>

    <el-drawer
      v-if="isEdit"
      title="图片爬取配置"
      :visible.sync="crawlingConfigdRawerVisible"
      direction="rtl"
      size="80%"
    >
      <CrawlingConfig/>
    </el-drawer>

    <!-- 新增任务对话框 -->
    <el-dialog :visible.sync="dialogVisible" width="90%" :close-on-click-modal="false" title="新增爬取任务">
      <template>
        <el-form :model="newTaskForm" label-width="120px">
          <el-form-item label="网页URL">
            <el-input :disabled="isUpdate"   type="textarea" rows="10" v-model="newTaskForm.urls" placeholder="请输入图片所在网页的 URL(多个逗号分隔)"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader
              v-model="newTaskForm.alltypeid"
              :props="{ checkStrictly: true, value: 'id',label: 'name' }"
              :options="typeList"
              placeholder="请选择分类"
              style="width: 100%;"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="newTaskForm.title"></el-input>
          </el-form-item>
<!--          <el-form-item label="是否保存图片">-->
<!--            <el-radio-group v-model="newTaskForm.isSave">-->
<!--              <el-radio :label="0">否</el-radio>-->
<!--              <el-radio :label="1">是</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
        </el-form>
      </template>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitNewTask">确定</el-button>
      </template>
    </el-dialog>

    <div class="flex-1 flex-col" style="min-height: 0;overflow: hidden">
      <!-- 历史记录列表 -->
      <div v-if="historyRecords.length > 0" class="history-card-container overflow-auto">
        <el-row :gutter="12" style="margin: 0;">
          <el-col :span="24" :md="12" :lg="8" v-for="record in historyRecords" :key="record.id" style="padding: 6px;">
            <el-card class="history-card" style="min-height: 250px; max-height: 310px;">

              <div class="flex-row align-center">
                <el-checkbox v-model="record.selected" @click="handleHistorySelect(record)"
                ></el-checkbox>
                <div class="flex-1"></div>
                <div class="flex-row" style="gap:5px;">
                  <el-button type="info" icon="el-icon-refresh" circle size="mini" @click="getCrawlInfo(record.id)" title="刷新"></el-button>
                  <el-button type="success" icon="el-icon-edit" circle size="mini" @click="editRow(record)" title="刷新"></el-button>
                  <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="confirmDeleteBill(record.id)"  title="删除"></el-button>
                </div>
              </div>

              <div class="history-card-content" @click.stop="handleCardClick(record)">
                <p class="text-overflow-hidden"><strong>批次ID：</strong> {{ record.id }}</p>
                <p class="text-overflow-hidden"><strong>爬取URL：</strong>
                  <el-popover
                    placement="top-start"
                    title="爬取URL"
                    width="400"
                    trigger="hover"
                    :content="record.urls">
                    <span slot="reference">{{ record.urls }}</span>
                  </el-popover>
                </p>
                <p><strong>状态：</strong>
                  <el-tag :type="getColor(record.status)">{{ record.statusName }}</el-tag>
                </p>
                <p class="text-overflow-hidden"><strong>备注：</strong>{{ record.title }}</p>
                <p class="text-overflow-hidden"><strong>描述： </strong>
                  <el-popover
                    placement="top-start"
                    title="描述"
                    width="400"
                    trigger="hover"
                    :content="record.description">
                    <span slot="reference">{{ record.description }}</span>
                  </el-popover>
                </p>
              </div>
              <div class="history-card-actions" v-if="isEdit">
                <el-button type="success" size="mini" @click="openThumbnailDrawer(record.id)" v-if="record.status === 'COMPLETED'">爬取结果</el-button>
                <el-button type="warning" size="mini" @click="confirmCrawlAgain(record.id)">重新爬取</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-divider style="margin: 0 !important;"></el-divider>
      <div class="flex-row justify-center align-center">
        <div class="flex-row" style="margin-left: 12px;">
          <el-checkbox v-model="isHistoryAllSelected" @change="handleHistorySelectAll">全选/反选</el-checkbox>
        </div>
        <div class="flex-1"></div>
        <pagination
          style="margin: 0 !important; height: 40px"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getHistoryRecords"
        />
      </div>
    </div>

    <!-- 爬取列表抽屉 -->
    <el-drawer
      title="爬取列表"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="90%"
      append-to-body
      z-index="10002"
    >
      <div class="fill-width-height flex-col">
        <div style="padding:0 12px 12px 12px;">
          <el-button type="primary" size="small" @click="confirmBatchDownImages()">多选下载</el-button>
          <el-button type="danger" size="small" @click="confirmBatchDeleteImages()">多选删除</el-button>
        </div>
        <el-divider style="margin: 0 !important;"/>
        <div v-if="thumbnailIds.length > 0" class="thumbnail-card-container align-center justify-start overflow-auto flex-1">
          <el-card v-for="item in thumbnailIds" :key="item.imageId" class="thumbnail-card flex-col" @click.native="handleCardClick(item)">
            <template #header>
             <div class="flex-row" >
               <el-checkbox
                 v-model="item.selected"
                 @change="handleThumbnailSelect(item)"
               ></el-checkbox>
               <div class="flex-1"></div>
               <div class="flex-row" style="gap: 10px">
                 <el-button type="text" text @click="copyPath(item.imageSrc)" >复制路径</el-button>
                 <el-button type="text" text @click="confirmDeleteImage(item.imageId)" style="color: red;">删除</el-button>
               </div>
             </div>
            </template>
            <div class="fill-width-height flex-col flex-1 " style="min-height: 0;" >
              <div class="flex-1" style="min-height: 0;" >
                <LazyLoadImage :src="item.imageSrc"></LazyLoadImage>
              </div>
            </div>
          </el-card>
        </div>
        <div v-if="thumbnailIds.length > 0" class="page_content flex-row">
          <div class="flex-row" style="margin-left: 12px;">
            <el-checkbox v-model="isAllSelected" @change="handleSelectAll">全选/反选</el-checkbox>
          </div>
          <div class="flex-1"></div>
          <pagination
            :total="thumbnailTotal"
            :page.sync="thumbnailQueryParams.pageNum"
            :limit.sync="thumbnailQueryParams.pageSize"
            @pagination="getThumbnailList"
            :page-sizes="[50, 100, 200, 500,1000,2000]"
            style="margin: 0 !important; padding: 0 !important;"
          />
        </div>
        <div v-if="!thumbnailIds.length" class="d-flex align-center justify-center">暂无缩略图记录</div>
      </div>
    </el-drawer>

    <EditAllImage ref="editAllImage"/>

    <ConfirDelDialog ref="confirDelDialog" @handleConfirm="handleConfirm"></ConfirDelDialog>

    <WeChatArticleSubscription ref="weChatArticleSubscriptionRef"/>

  </div>
</template>

<script>
import {
  billPage,
  billDetailPage,
  save,
  submitTaskById,
  deleteImage,
  crawlAgain,
  deleteBill, update
} from '@/api/imgManage/imageCrawler'
import CrawlingConfig from '@/views/imgManage/appConfig/crawlingConfig.vue'
import TypeMenu from '@/views/imgManage/typeMenu/index.vue'
import { getList } from '@/api/imgManage/imgType'
import { listToTree } from '@/utils'
import Item from '@/views/imgManage/typeMenu/item.vue'
import LazyLoadImage from '@/components/LazyLoadImage'
import ConfirDelDialog from '@/views/imgManage/imageCrawler/confirDelDialog.vue'
export default {
  components: {
    ConfirDelDialog,
    Item,
    TypeMenu,
    CrawlingConfig,
    LazyLoadImage,
    EditAllImage: () => import('./editAllImage'),

    WeChatArticleSubscription: () => import('./weChatArticleSubscription/index.vue'),
  },
  props: {
    isEdit: {
      type: Boolean,
      default: () => true
    }
  },
  data() {
    return {
      deleteSelectedIds: '',
      activeId: 'all',
      allObj: { value:'all', label: '全部' ,id:'all', name: '全部', level: 1 },
      typeList: [],
      historyRecords: [],
      drawerVisible: false,
      dialogVisible: false,
      crawlingConfigdRawerVisible: false,
      thumbnailIds: [],
      newTaskForm: {
        urls: '',
        title: '',
        alltypeid: '',
        isSave: 0
      },
      // 历史记录分页相关变量
      queryParams: {
        pageNum: 1,
        pageSize: 12
      },
      total: 0,
      // 缩略图分页相关变量
      thumbnailQueryParams: {
        pageNum: 1,
        pageSize: 200
      },
      thumbnailTotal: 0,
      currentBillId: null, // 记录当前打开缩略图列表对应的批次 ID
      selectedHistoryIds: [], // 存储选中的历史任务 ID
      selectedThumbnailUrls: [], // 存储选中的缩略图 URL
      isAllSelected: false,
      isHistoryAllSelected: false,
      isUpdate: false,
    }
  },
  async mounted() {
    await this.initTypeList()
    await this.getHistoryRecords()
  },
  methods: {
    addTask(){
      this.dialogVisible = true
      this.newTaskForm = {
        urls: '',
        title: '',
        isSave: 0
      }
      this.isUpdate = false
    },
    subscription(){
      this.$refs.weChatArticleSubscriptionRef.init()
    },
    editAllImage(){
      this.$refs.editAllImage?.showDialog()
    },
    editRow(row){
      this.dialogVisible = true
      this.isUpdate = true
      const rowObj = JSON.parse(JSON.stringify(row))
      rowObj.alltypeid = row.alltypeid?.split(',')
      this.$set(this,'newTaskForm', rowObj)
    },
    setting() {
      this.crawlingConfigdRawerVisible = true
    },
    clickType(){
      this.getHistoryRecords()
    },
    async copyPath(imageSrc) {
      try {
        await navigator.clipboard.writeText(imageSrc);
        this.$message.success('复制成功')
      } catch (error) {
        console.error('复制失败:', error);
      }
    },
    // 获取历史记录
    async getHistoryRecords() {
      try {
        const params = Object.assign(this.queryParams,{ 'alltypeid':  this.activeId })
        const response = await billPage(params)
        this.historyRecords = response.rows
        this.total = response.total || 0
      } catch (error) {
        console.error('获取历史记录失败', error)
      }
    },
    deleteBills(){
      const ids = this.historyRecords
        .filter(item => item.selected)
        .map(item => item.id)
        .join(',')
      this.confirmDeleteBill(ids)
    },
    async confirmDeleteBill(ids) {
      let length = ids.split(',').length
      this.$confirm(`确定要删除这${length}个任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.deleteBill(ids)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async deleteBill(ids) {
      try {
        await deleteBill({ ids: ids })
        this.$message.success('删除任务成功')
        await this.getHistoryRecords()
      } catch (error) {
        this.$message.error('删除任务失败' + error)
      }
    },
    // 提交新任务
    async handleSubmitNewTask() {
      if (!this.newTaskForm.urls) {
        this.$message.warning('请输入图片所在网页的 URL')
        return
      }
      if(this.newTaskForm.alltypeid instanceof Array){
        this.newTaskForm.alltypeid = this.newTaskForm.alltypeid.join(',')
      }
      try {
        let saveResponse = null
        if(this.newTaskForm.id){
          saveResponse = await update(this.newTaskForm)
        } else {
          saveResponse = await save(this.newTaskForm)
        }
        if(!this.isUpdate){
          const billId = saveResponse.data.id
          await submitTaskById({ id: billId })
          this.$message.success('任务已提交')
        } else {
          this.$message.success('修改成功')
        }
        this.dialogVisible = false
        await this.getHistoryRecords()
      } catch (error) {
        console.error('提交新任务失败', error)
        this.$message.error('提交新任务失败')
      }
    },
    // 刷新状态
    async getCrawlInfo(billId) {
      try {
        await this.getHistoryRecords()
        this.$message.success('状态已刷新')
      } catch (error) {
        console.error('刷新状态失败', error)
        this.$message.error('刷新状态失败')
      }
    },
    // 打开缩略图抽屉
    async openThumbnailDrawer(billId) {
      this.currentBillId = billId
      this.thumbnailQueryParams.pageNum = 1 // 打开抽屉时重置页码为 1
      await this.getThumbnailList()
      this.drawerVisible = true
    },
    // 获取缩略图列表
    async getThumbnailList() {
      try {
        const params = {
          crawlerBillId: this.currentBillId,
          ...this.thumbnailQueryParams
        }
        const response = await billDetailPage(params)
        this.thumbnailIds = response.rows.map(item => ({
          imageId: item.id,
          imageSrc: item.imageUrl
        }))
        this.thumbnailTotal = response.total || 0 // 更新缩略图总记录数
      } catch (error) {
        console.error('获取缩略图列表失败', error)
        this.$message.error('获取缩略图列表失败')
      }
    },
    async confirmCrawlAgain(billId) {
      this.$confirm('确定要重新爬取该任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.crawlAgain(billId)
      }).catch(() => {
        this.$message.info('已取消重新爬取')
      })
    },
    // 重新爬取
    async crawlAgain(billId) {
      try {
        await crawlAgain({ id: billId })
        this.$message.success('任务已重新提交')
        await this.getHistoryRecords()
        setTimeout(() => {
          this.getHistoryRecords()
        }, 3000)
      } catch (error) {
        console.error('重新爬取失败', error)
        this.$message.error('重新爬取失败')
      }
    },
    getColor(status){
      if(status === 'COMPLETED'){
        return 'success'
      } else if(status === 'FAILED') {
        return 'danger'
      } else{
        return 'warning'
      }
    },
    async confirmDeleteImage(imageId) {
      // this.$confirm('确定要删除该图片吗？', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(async() => {
      //   await this.deleteImage(imageId)
      // }).catch(() => {
      //   this.$message.info('已取消删除图片')
      // })
      await this.confirmBatchDeleteImages(imageId)
    },
    async handleConfirm(check){
      this.$modal.loading("正在处理数据，请稍候...");
      await this.deleteImage( this.deleteSelectedIds,check)
      this.$refs.confirDelDialog.closeDialog()
      this.$modal.closeLoading()
    },
    // 多选下载图片
    async confirmBatchDownImages() {
      // 获取所有选中的图片
      const selectedImages = this.thumbnailIds.filter(item => item.selected)
      if (selectedImages.length === 0) {
        this.$message.warning('请选择要下载的图片')
        return
      }

      // 处理下载逻辑
      try {
        // 批量下载可能会被浏览器限制，这里采用延迟逐个下载的方式
        selectedImages.forEach((item, index) => {
          setTimeout(() => {
            this.downloadSingleImage(item.imageSrc)
          }, index * 100) // 每个下载间隔500ms，避免浏览器拦截
        })
        this.$message.success(`已开始下载${selectedImages.length}张图片`)
      } catch (error) {
        console.error('批量下载失败', error)
        this.$message.error('下载失败，请重试')
      }
    },
    // 下载单张图片
    downloadSingleImage(imageUrl) {
        const link = document.createElement("a");
        link.href = imageUrl;
        link.target = "_blank";
        link.rel = "noopener noreferrer";
        link.download = `image_${Date.now()}.jpg`
        link.click();
    },
    async confirmBatchDeleteImages(imageId) {
      this.deleteSelectedIds = ''
      const selectedIds = imageId ? [imageId] : this.thumbnailIds
        .filter(item => item.selected)
        .map(item => item.imageId)
      if (selectedIds.length === 0) {
        this.$message.warning('请选择要删除的图片')
        return
      }
      this.deleteSelectedIds = selectedIds.join(',')
      this.$refs.confirDelDialog.showDialog()
    },
    // 删除图片
    async deleteImage(imageId,isAddBlackList) {
      try {
        this.isAllSelected = false
        await deleteImage({ fildIds: imageId, isAddBlackList: isAddBlackList })
        this.$message.success('图片已删除')
        this.thumbnailIds = this.thumbnailIds.filter(item => item.imageId !== imageId)
        await this.getThumbnailList() // 删除后重新获取缩略图列表
      } catch (error) {
        console.error('删除图片失败', error)
        this.$message.error('删除图片失败')
      }
    },
    handleCardClick(item) {
      this.$set(item,'selected',!item.selected)
    },
    handleHistorySelect(item) {

    },
    handleThumbnailSelect(item) {

    },
    handleHistorySelectAll(){
      this.historyRecords.forEach(item => {
        item.selected = this.isHistoryAllSelected
      })
    },
    handleSelectAll() {
      this.thumbnailIds.forEach(item => {
        item.selected = this.isAllSelected
      })
    },
    async initTypeList(){
      const dataList = await getList({ bustype: 'imgType' }).then(res => res.data )
      dataList.forEach((item) => {
        item.label = item.name
        item.value = item.id
      })
      const treeList = listToTree(dataList,'id','parentid')
      treeList.unshift(this.allObj)
      this.typeList = treeList
    },
  }
}
</script>

<style scoped>
.thumbnail-card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 0 12px;
  justify-content: center;
}
.page_content{
  height: 50px;
  border-top: 1px solid rgb(227, 227, 227);
  justify-content: center;
  align-items: center;
}

.thumbnail-card {
  width: 200px;
  min-height: 300px; /* 设置最小高度，可根据实际情况调整 */
  display: flex;
  flex-direction: column;

  ::v-deep .el-card__body {
    flex: 1;
  }

  .el-image {
    flex: 1; /* 让图片部分占据剩余空间 */
    min-height: 0; /* 防止图片溢出 */
  }
}


.card-actions {
  margin-top: 12px;
  text-align: center;
}

.history-card-container {
  margin-top: 12px;
}

.history-card {
  width: 100%;
  cursor: pointer;
}

.history-card:hover{
  background-color: #ecf5ff;
}

.history-card-content {
  padding: 12px;
  padding-top: 0;
}

.history-card-actions {
  padding: 0 12px 12px;
  text-align: center;
}

::v-deep{
  .el-divider--horizontal{
    margin: 0 !important;
  }
}

</style>
